package com.chaodev.base.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dto.ClockDistanceDto;
import com.chaodev.base.dto.LunBoDto;
import com.chaodev.base.model.*;
import com.chaodev.base.service.CommService;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.utils.JwtUtil;
import com.chaodev.base.utils.QrCodeGenerate;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * vcbase
 *
 * @author 95634
 * @描述
 * @date 2023/5/18 18:21
 **/
@RequestMapping("comm")
@RestController
public class CommController {
    @Autowired
    CommService commService;

    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;

    @PostMapping("/getWaitTask")
    @ApiOperation("获取待办")
    public Result getWaitTask(@RequestBody Task dto, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            dto.setCUser(userInfo.getUserId());
            dto.setDepId(userInfo.getDepartId());
            if(dto.getPage()==0){
                dto.setPage(1);
            }
            if(dto.getRows()==0){
                dto.setRows(20);
            }
            PageHelper.startPage(dto.getPage(),dto.getRows());
            List<Task> myWaitTask = commService.getMyWaitTask(dto);
            PageInfo<Task> taskPageInfo = new PageInfo<>(myWaitTask, dto.getRows());
            Map<String, Object> map=new HashMap<>();
            map.put("total",taskPageInfo.getTotal());
            map.put("list",taskPageInfo.getList());
            result.setCode(200);
            result.setMsg("获取数据成功");
            result.setData(map);
            logService.logAdd(null, "获取待办", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("请重新登录");
            logService.logAdd(null, "获取待办", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping("/getDoneTask")
    @ApiOperation("获取已办")
    public Result getDoneTask(@RequestBody Task dto, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            dto.setCUser(userInfo.getUserId());
            PageHelper.startPage(dto.getPage(),dto.getRows());
            List<Task> myWaitTask = commService.getMyDoneTask(dto);
            PageInfo<Task> taskPageInfo = new PageInfo<>(myWaitTask, dto.getRows());
            Map<String, Object> map=new HashMap<>();
            map.put("total",taskPageInfo.getTotal());
            map.put("list",taskPageInfo.getList());
            result.setCode(200);
            result.setMsg("获取数据成功");
            result.setData(map);
            logService.logAdd(null, "获取已办", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("请重新登录");
            logService.logAdd(null, "获取已办", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping("/completeTask")
    @ApiOperation("处理任务")
    public Result completeTask(@RequestBody TaskComplete dto, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            dto.setOper(userInfo.getUserId());
            commService.completeTask(dto);
            result.setCode(200);
            result.setMsg("处理成功");
            logService.logAdd(null, "处理任务", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("请重新登录");
            logService.logAdd(null, "处理任务", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @GetMapping("/goToWx")
    public void goToWx(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.sendRedirect("https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI1NjUwNDkxNA==#wechat_redirect");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Autowired
    private QrCodeGenerate codeGenerate;

    @PostMapping("/getGenerateQr")
    @ApiOperation("获取二维码图片")
    public Result getGenerateQr(String content, HttpServletResponse servletResponse) {
        Result result = new Result();
        try {
            if (content == null || "".equals(content)) {
                result.setCode(ResultEnum.BADREQUEST.getCode());
                result.setMsg("缺少转换内容");
                return result;
            }
            codeGenerate.createCodeToStream(content, servletResponse);
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        }
        return result;
    }

    @Autowired
    private UploadNewController uploadNewController;

    @PostMapping("/getGenerateQrUrl")
    @ApiOperation("获取二维码图片url")
    public Result getGenerateQrUrl(String content, String qrName, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        try {
            if (content == null || "".equals(content)) {
                result.setCode(ResultEnum.BADREQUEST.getCode());
                result.setMsg("缺少转换内容");
                return result;
            }
            qrName = qrName == null ? "qrCode" : qrName;
            MultipartFile[] file = new MultipartFile[1];
            String lastContent = content.replaceAll("<p>", "").replaceAll("</p>", "");
            file[0] = codeGenerate.createCodeToMultipartFile(lastContent, qrName);
            return uploadNewController.uploadhostFile(file, request);
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        }
        return result;
    }

    @PostMapping("/getData")
    @ApiOperation("通过任务信息找具体的数据")
    public Result getData(@RequestBody Task task, HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            //校验数据
            if (task.getBizId() == null || task.getBizType() == null) {
                result.setCode(500);
                result.setMsg("缺少参数");
                logService.logAdd(null, "通过任务信息找具体的数据", "ERROR", result.toString(), userInfo, request);
            }

            //数据处理
            Map<String, Object> data = commService.getData(task);

            result.setCode(200);
            result.setMsg("获取数据成功");
            result.setData(data);
            logService.logAdd(null, "获取待办", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("请重新登录");
            logService.logAdd(null, "通过任务信息找具体的数据", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getVolunteerActivityStatistic")
    @ApiOperation(value = "获取志愿者和活动统计数据")
    @ResponseBody
    public Result getVolunteerActivityStatistic(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            result.setData(commService.getVolunteerActivityStatistic(map));
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("查询成功");
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(map.toString(), "获取志愿者和活动统计数据", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * 获取轮播图分页列表
     *
     * @param dto
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author zyf
     * @date 2023-09-20 10:32
     */
    @ApiOperation(value = "获取轮播图分页列表", notes = "获取轮播图分页列表")
    @PostMapping("getLunBoList")
    public Result getLunBoList(@RequestBody @Validated LunBoDto dto, HttpServletRequest request) {
        Result result;
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            PageInfo<LinkedHashMap<String, Object>> lunBoPageList = commService.getLunBoPageList(dto);
            Map<String, Object> resultMap = new HashMap<>(2);
            resultMap.put("total", lunBoPageList.getTotal());
            resultMap.put("list", lunBoPageList.getList());
            result = Result.success(resultMap, "轮播图分页列表获取成功！");
        } else {
            result = Result.complete(-1, "登录超时", null);
        }
        logService.logAdd(dto.toString(), "获取轮播图分页列表列表分页", (result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR"), result.toString(), userInfo, request);
        return result;
    }

    /**
     * 轮播图新增或编辑
     *
     * @param lunBoList
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author zyf
     * @date 2023-09-20 10:53
     */
    @ApiOperation(value = "轮播图新增或编辑", notes = "轮播图新增或编辑")
    @PostMapping("saveLunBo")
    public Result saveLunBo(@RequestBody List<LunBo> lunBoList, HttpServletRequest request) {
        if (lunBoList.stream().anyMatch(lunBo -> StringUtils.isBlank(lunBo.getPicType()) || StringUtils.isBlank(lunBo.getPicName()) || StringUtils.isBlank(lunBo.getPicUrl()) || StringUtils.isBlank(lunBo.getPicLink()) || null == lunBo.getSort())) {
            return Result.error("参数picType|picName|picUrl|picLink|sort为必传项！");
        }
        Result result = Result.success();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            for (LunBo lunBo : lunBoList) {
                if (null == lunBo.getId()) {
                    lunBo.setState(1);
                    lunBo.setCreateUser(userInfo.getUserId());
                }
                commService.saveLunBo(lunBo);
            }
        } else {
            result = Result.complete(-1, "登录超时", null);
        }
        logService.logAdd(lunBoList.toString(), "轮播图新增或编辑", (result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR"), result.toString(), userInfo, request);
        return result;
    }

    /**
     * 轮播图删除
     *
     * @param dto
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author zyf
     * @date 2023-09-20 11:41
     */
    @ApiOperation(value = "轮播图删除", notes = "轮播图删除")
    @PostMapping("delLunBo")
    public Result delLunBo(@RequestBody LunBoDto dto, HttpServletRequest request) {
        if (null == dto.getIds() || dto.getIds().size() == 0) {
            return Result.error("参数ids为必传项！");
        }
        Result result = Result.success();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            commService.delLunBo(dto.getIds());
        } else {
            result = Result.complete(-1, "登录超时", null);
        }
        logService.logAdd(dto.toString(), "轮播图删除", (result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR"), result.toString(), userInfo, request);
        return result;
    }

    /**
     * 检查打卡距离
     *
     * @param distance
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author zyf
     * @date 2023-09-20 17:58
     */
    @ApiOperation(value = "检查打卡距离", notes = "检查打卡距离")
    @PostMapping("chkClockDistance")
    public Result chkClockDistance(@RequestBody ClockDistance distance, HttpServletRequest request) {
        if (StringUtils.isBlank(distance.getCsys()) || null == distance.getLng() || null == distance.getLat()) {
            return Result.error("参数csys|lng|lat为必传项！");
        }
        Result result = Result.success();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        boolean chkFlag = true;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            //获取本部门或配置过的首个直属上级部门
            ClockDistance distanceT = commService.getClockDistance(userInfo.getDepartId(), distance.getCsys());
            if (null == distanceT) {
                return Result.success(true);
            }
            switch (distance.getCsys()) {
                case "WGS84":
                    break;
                case "GCJ02":
                    break;
                case "BD09":
                    break;
                case "WEMAP":
                    //地球半径（km）
                    double earthRadius = 6378.137;

                    double radLat1 = distance.getLat().doubleValue() * Math.PI / 180.0;
                    double radLng1 = distance.getLng().doubleValue() * Math.PI / 180.0;
                    double radLat2 = distanceT.getLat().doubleValue() * Math.PI / 180.0;
                    double radLng2 = distanceT.getLng().doubleValue() * Math.PI / 180.0;
                    double a = radLat1 - radLat2;
                    double b = radLng1 - radLng2;

                    double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                            + Math.cos(radLat1) * Math.cos(radLat2)
                            * Math.pow(Math.sin(b / 2), 2)));

                    s = s * earthRadius;

                    s = Math.round(s * 10000d) / 10000d;

                    s = s * 1000;

                    chkFlag = distanceT.getDistance() > Math.abs(s);
                    break;
                default:
                    break;
            }
            result.setData(chkFlag);
        } else {
            result = Result.complete(-1, "登录超时", null);
        }
        logService.logAdd(distance.toString(), "检查打卡距离", (result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR"), result.toString(), userInfo, request);
        return result;
    }

    /**
     * 打卡距离新增或编辑
     *
     * @param distance
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author zyf
     * @date 2023-09-20 18:41
     */
    @ApiOperation(value = "打卡距离新增或编辑", notes = "打卡距离新增或编辑")
    @PostMapping("saveClockDistance")
    public Result saveClockDistance(@RequestBody ClockDistance distance, HttpServletRequest request) {
        if (StringUtils.isBlank(distance.getCsys()) || null == distance.getLng() || null == distance.getLat() || null == distance.getDistance()) {
            return Result.error("参数csys|lng|lat|distance为必传项！");
        }
        Result result = Result.success();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            if (null == distance.getId()) {
                distance.setDepartId(userInfo.getDepartId());
                distance.setState(1);
                distance.setCreateUser(userInfo.getUserId());
            }
            commService.saveClockDistance(distance);
        } else {
            result = Result.complete(-1, "登录超时", null);
        }
        logService.logAdd(distance.toString(), "打卡距离新增或编辑", (result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR"), result.toString(), userInfo, request);
        return result;
    }

    /**
     * 打卡距离删除
     *
     * @param dto
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author zyf
     * @date 2023-09-20 18:38
     */
    @ApiOperation(value = "打卡距离删除", notes = "打卡距离删除")
    @PostMapping("delClockDistance")
    public Result delClockDistance(@RequestBody ClockDistanceDto dto, HttpServletRequest request) {
        if (null == dto.getIds() || dto.getIds().size() == 0) {
            return Result.error("参数ids为必传项！");
        }
        Result result = Result.success();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            commService.delClockDistance(dto.getIds());
        } else {
            result = Result.complete(-1, "登录超时", null);
        }
        logService.logAdd(dto.toString(), "打卡距离删除", (result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR"), result.toString(), userInfo, request);
        return result;
    }

    /**
     * 获取轮播图分页列表
     *
     * @param dto
     * @param request
     * @return com.kmvc.vcbase.model.Result
     * @author zyf
     * @date 2023-09-20 10:32
     */
    @ApiOperation(value = "获取轮播图分页列表", notes = "获取轮播图分页列表")
    @PostMapping("getLunBoListOut")
    public Result getLunBoListOut(@RequestBody @Validated LunBoDto dto, HttpServletRequest request) {
        Result result;
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("网页访问");
        PageInfo<LinkedHashMap<String, Object>> lunBoPageList = commService.getLunBoPageList(dto);
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("total", lunBoPageList.getTotal());
        resultMap.put("list", lunBoPageList.getList());
        result = Result.success(resultMap, "轮播图分页列表获取成功！");
        logService.logAdd(dto.toString(), "获取轮播图分页列表列表分页", (result.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR"), result.toString(), userInfo, request);
        return result;
    }
}
